import React from 'react'
import {NavLink,useNavigate} from 'react-router-dom'
import cookie from "react-cookies";
import api from '../../api'

import './index.css'
import {createLogin, createLogout} from "../../redux/actions/login";
import {connect} from "react-redux";


function User(props){
    const navigate=useNavigate()

    //退出登录
    async function quitLogin() {
        let data=await api.loginOutApi()
        console.log(data.message,data.status)
        cookie.remove('user-token')
        props.logout(true)
    }
    //个人中心
    function toUser(){
        if(cookie.load('user-token')){
            navigate('/user')
        }else {
            props.logout(true)
        }
    }

    function showUser(){
        if(props.loginState||cookie.load('user-token'))
        {
            return (
                <div className="dropdown user">
                    <span className={'dropdown-toggle iconfont icon-yonghu-yuan'} data-toggle="dropdown"/>
                    <ul className="dropdown-menu" aria-labelledby="dropdownMenuLink" >
                        <li className={'dropdown-item'}><button onClick={toUser}>个人中心</button></li>
                        <li className={'dropdown-item'}><button onClick={quitLogin}>退出登录</button></li>
                    </ul>
                </div>
            )
        }
        else
        {
            return <NavLink to={'/login'}>登录/注册</NavLink>
        }
    }

    return (
        showUser()
    )
}
//创建容器组件
//向ui组件传递状态对象
function mapStateToProps(state){
    return{
        loginState:state.loginState
    }
}
//向ui组件传递操作状态对象的方法
function mapDispatchToProps(dispatch){
    return{
        login:(data)=>{dispatch(createLogin(data))},
        logout:(data)=>{dispatch(createLogout(data))}
    }
}
//连接容器组件与ui组件
const UserContainer=connect(mapStateToProps,mapDispatchToProps)(User)
export default UserContainer